// pages/homePage/health/health.js
const app = getApp();
const {
  total_standards_child,
  total_standards_young,
  total_standards_adult,
  start_standards_child,
  start_standards_young,
  start_standards_adult,
  wake_standards,
  deep_standards_child,
  deep_standards_young,
  deep_standards_adult,
  heartRate_standards,
  step_standards_child,
  step_standards_young,
  step_standards_adult
} = require("../../../utils/standards-score.js");
// import F2 from '@antv/wx-f2';
// let chart = null;
// F2.Global.setTheme({
//   appendPadding: [5, 15, 5, 15]
// });

// function initChart(canvas, width, height) { // 使用 F2 绘制图表
//   const data = [{
//     y: 0,
//     x: "周一"
//   }, {
//     y: 60,
//     x: "周二"
//   }, {
//     y: 90,
//     x: "周三"
//   }, {
//     y: 85,
//     x: "周四"
//   }, {
//     y: 80,
//     x: "周五"
//   }, {
//     y: 80,
//     x: "周六"
//   }, {
//     y: 0,
//     x: "周日"
//   }]
//   chart = new F2.Chart({
//     el: canvas,
//     width: width,
//     height: height
//   });

//   chart.source(data, {
//     y: {
//       ticks: [0, 20, 40, 60, 80, 100]
//     }
//   });
//   chart.tooltip(false);
//   chart.axis('x', {
//     label(text, index, total) {
//       const textCfg = {};
//       if (index === 0) {
//         textCfg.textAlign = 'left';
//       } else if (index === total - 1) {
//         textCfg.textAlign = 'right';
//       }
//       return textCfg;
//     }
//   });

//   let barWidth = 30 * (wx.getSystemInfoSync().windowWidth / 375) / 2;

//   chart.area().position('x*y').color('l(90) 0:#44ABFF 1:#ffffff').shape('smooth');
//   chart.line().position('x*y').color('#44ABFF').shape('smooth');

//   data.map(obj => {
//     chart.guide().text({
//       position: [obj.x, obj.y],
//       content: obj.y,
//       style: {
//         textAlign: 'start',
//         fontFamily: "PingFangSC-Regular",
//         fontSize: 20,
//         fill: "#44ABFF"
//       },
//       offsetX: -10,
//       offsetY: -10
//     });
//   })

//   chart.render();
//   return chart;
// }

Page({

  /**
   * 页面的初始数据
   */
  data: {
    healthScore: 0,
    name: "",
    headImg: "",
    rank: "",
    bmi: 0,
    bmiLevel: "",
    position: "",
    bg: "",
    className: "",
    currentDate: "",
    age:""
    // opts: {
    //   onInit: initChart
    // }
  },
  onLoad: function(options) {
    let bmi = this.calcBmi();
    let css = this.clacPosition(bmi);
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; //上一个页面
    this.setData({
      headImg: wx.getStorageSync("student").gender == 1 ? "/static/images/male_head.png" : "/static/images/female_head.png",
      name: wx.getStorageSync("student").name,
      healthScore: prevPage.data.healthScore,
      currentDate: prevPage.data.now,
      bmi: bmi,
      age:prevPage.data.age,
      position: css[0] - 45 + "rpx",
      bg: css[1],
      className: css[2],
      bmiLevel: css[3],
    })

    this.getRank();
  },
  //计算bmi
  calcBmi() {
    // 体质指数（BMI）=体重（kg）÷身高 ^ 2（m）
    let bmi = 0;
    let height = wx.getStorageSync("height");
    let weight = wx.getStorageSync("weight");

    if (height && weight) {
      bmi = weight / Math.pow(height / 100, 2);
      bmi = bmi.toFixed(1) * 1;
    }
    return bmi;
  },
  //计算bmi的位置
  clacPosition(bmi) {
    let min = 55,
      bg, className, bmiLevel,
      position = 0;

    if (bmi <= 15.2) {
      position = bmi / 15.2 * 160 + 55;
      bg = "#ffd666";
      bmiLevel = "偏轻";
      className = "y";
    } else if (bmi <= 22.2) {
      position = (bmi - 15.2) / 7 * 160 + 55 + 160;
      bg = "#69c0ff";
      bmiLevel = "正常";
      className = "b";
    } else if (bmi <= 24.8) {
      position = (bmi - 22.2) / 2.6 * 160 + 55 + 160 * 2;
      bg = "#ff7875";
      bmiLevel = "偏胖";
      className = "p";
    } else {
      bmi = bmi >= 30 ? 30 : bmi;
      position = (bmi - 24.8) / 5.2 * 160 + 55 + 160 * 3;
      bg = "#ff4d4f";
      bmiLevel = "肥胖";
      className = "r";
    }

    return [position, bg, className, bmiLevel];
  },
  //获取体质健康指数数据
  getRank() {
    let that = this;
    app.api.ajaxSubmit("/node/wx/home/getRankData", {
      classId: wx.getStorageSync("student").classId,
      date: this.data.currentDate
    }).then(response => {
      let data = response.data.data;
      if (data && data.length) {
        that.calcRank(data);
      }
    }).catch(err => {})
  },
  //计算排名
  calcRank(list) {
    let scoreArr = [];
    list.forEach(item => {
      let braceleInfo = item.braceleInfo;
      let testInfo = item.testInfo;
      let arr = Object.keys(testInfo);
      let testScore = arr.length ? testInfo.score / 100 : 0;
      let testLevel = arr.length ? testInfo.level : -99999;

      let sleepScore = braceleInfo.stepPass == 2 ? 0 : this.getSleepScore(braceleInfo.sleepData);
      let keysArr = Object.keys(braceleInfo.heartRateData);
      let heartRate = braceleInfo.heartRatePass == 2 || !keysArr.length ? 0 : braceleInfo.heartRateData.averageHeartRate;
      let heartRateScore = this.calcHeartScore(heartRate);
      let stepNum = braceleInfo.stepPass == 2 ? 0 : braceleInfo.stepData;
      let setpScore = this.calcStepScore(stepNum);

      let healthScore = this.calcHealthScore(testScore, sleepScore, heartRateScore, setpScore);
      scoreArr.push(healthScore);
    })
    let scores = [...scoreArr].sort(function(a, b) {
      return a - b;
    }).reverse();
    this.setData({
      rank: scores.indexOf(this.data.healthScore) + 1 + "/" + scores.length
    })
  },
  //计算睡眠得分
  getSleepScore(option) {
    let sleepLengthScore, sleepStartScore, wakeupScore, depthScore;
    let sleepTotal = option.sleepTotal / 3600;
    let sleepStart = new Date(option.sleepStartTime).getHours();
    // sleepStart = sleepStart < 12 ? (24 + sleepStart) : sleepStart;
    let wakeUpCount = option.wakeUpCountl;
    let depthPercent = option.depthPercent;
    if (sleepTotal == 0 || !option.sleepTotal) return 0;

    let total_standards, start_standards, deep_standards, rate = [];
    if (this.data.age < 13 && this.data.age >= 6) {
      total_standards = total_standards_child;
      start_standards = start_standards_child;
      deep_standards = deep_standards_child;
      rate = [0.4, 0.2, 0.15, 0.25];
    } else if (this.data.age < 17 && this.data.age >= 14) {
      total_standards = total_standards_young;
      start_standards = start_standards_young;
      deep_standards = deep_standards_young;
      rate = [0.35, 0.25, 0.15, 0.25];
    } else {
      total_standards = total_standards_adult;
      start_standards = start_standards_adult;
      deep_standards = deep_standards_adult;
      rate = [0.35, 0.3, 0.15, 0.2];
    }

    total_standards.some(item => {
      if (item.begin <= sleepTotal && sleepTotal < item.end) {
        sleepLengthScore = item.score;
        return true;
      }
    })

    start_standards.some(item => {
      if (item.begin <= sleepStart && sleepStart < item.end) {
        sleepStartScore = item.score;
        return true;
      }
    })

    wake_standards.some(item => {
      if (item.begin <= wakeUpCount && wakeUpCount < item.end) {
        wakeupScore = item.score;
        return true;
      }
    })

    deep_standards.some(item => {
      if (item.begin <= depthPercent && depthPercent < item.end) {
        depthScore = item.score;
        return true;
      }
    })

    let score = sleepLengthScore * rate[0] + sleepStartScore * rate[1] + wakeupScore * rate[2] + depthScore * rate[3];
    return score;
  },
  //计算心率得分
  calcHeartScore(heartRate) {
    let score = 0;
    if (heartRate == 0) return score;

    heartRate_standards.some(item => {
      if (item.begin <= heartRate && heartRate < item.end) {
        score = item.score;
        return true;
      }
    })

    return score;
  },
  //计算步数得分
  calcStepScore(stepNum) {
    let score = 0;
    if (stepNum == 0) return score;

    let step_standards;
    if (this.data.age < 13 && this.data.age >= 6) {
      step_standards = step_standards_child;
    } else if (this.data.age < 17 && this.data.age >= 14) {
      step_standards = step_standards_young;
    } else {
      step_standards = step_standards_adult;
    }

    step_standards.some(item => {
      if (item.begin <= stepNum && stepNum < item.end) {
        score = item.score;
        return true;
      }
    })

    return score;
  },
  //计算体质健康指数
  calcHealthScore(testScore, sleepScore, heartRateScore, setpScore) {
    let healthScore = 0;
    if (testScore == 0) {
      healthScore = (sleepScore * 0.35 + heartRateScore * 0.15 + setpScore * 0.15) / 0.65;
      healthScore = Math.round(healthScore);
    } else {
      healthScore = testScore * 0.35 + sleepScore * 0.35 + heartRateScore * 0.15 + setpScore * 0.15;
      healthScore = Math.round(healthScore);
    }

    return healthScore;
  },
  // 获取半年内的体质数据
  // getHealthDet() {
  //   let that = this;
  //   app.api.ajaxSubmit("/node/wx/home/getHealthDet", {
  //     studentNumber: wx.getStorageSync("student").studentNumber,
  //     deviceNum: wx.getStorageSync("deviceNum"),
  //     date: that.data.currentDate
  //   }).then(response => {
  //     let info = response.data.data;
  //     if (response.data.error == 10000 && info.length) {

  //     }
  //   }).catch(err => {
  //     wx.showToast({
  //       title: '服务器开小差',
  //       icon: "none",
  //       duration: 2000
  //     })
  //   })
  // }

})